var express = require('express');
var router = express.Router();
var file = require('../db/muitiparty');
var Promise = require('promise');
var config = require('../config');
var crypto = require('crypto');
var fs = require('fs');
var Comments = require('../db/commentsO');
var keep = require('../db/keep');
var fans = require('../db/fans');
var multiparty = require('multiparty')
var os = require('os')

var artTag = {"WorkEmotion":"工作.情感",
			  "CartoonNovel":"漫画.小说",
			  "MoviesComic":"影视.动漫",
			  "ScienceCulture":"科技.文化",
			  "MusicFashion":"音乐.时尚",};

function randomName(len){
	var strArr = '1234567890QAZXSWEDCVFRTGBNHYUJMKIOLPzaqwsxcderfvbgtyhnjuikop'
	var s = ''
	for (var i = 0; i < len; i++) {
		s += strArr[Math.ceil(Math.random()*60)]
	}
	return s
}

/*
* argument articleName(string), callback(function)
* return string?
*/
function readA(articleName, callback){
	fs.readFile(os.homedir()+'/A/'+articleName, function(err, date){
		if (err) {
			callback(null)
		} else {
			callback(date)
		}

	})
}
/* GET users listing. */

function encrypto(str){
    var cipher = crypto.createCipher('aes192', config.key);  
    var enc = cipher.update(str,'utf8','hex');  
    enc += cipher.final('hex');  
    return enc;  
}

router.get('/', function(req, res, next){
	res.render('articles',{'title':'article','user':req.infos});
});

router.get('/:id', function(req, res, next){
	if (req.params.id in artTag) {
		new Promise(function(resolve, reject){
			req.VandB.count({tag:req.params.id,type:"article",pass:true},function(err,result){
					if (err) {
					reject(err);
					}
					resolve(result);
				});
			}).then(function(count){
			if(!req.query.page || req.query.page==""){
				var	page = 1;
			} else {
				page = req.query.page;
			}

			skip = (page-1)*16;

			req.VandB.find({tag:req.params.id,type:"article",pass:true}).skip(skip).limit(16).toArray(function(err, items){
					res.render('artTag',{
						'title':artTag[req.params.id],
						'user':req.infos,
						'VA':items,
						'count':count,
						'page':page,
						'tag':req.params.id,
					})
			});
		});
	} else {
		return next();
	}
})


router.get('/post', function(req, res, next){
	if (req.infos!=null && req.infos!='' && req.infos) {
		res.render('article', {'title':'article','user':req.infos});
	} else {
		res.redirect('/log/login');
	}
})

router.post('/post', function(req, res, next){
	if (!req.VandB || !req.body.title || !req.body.content) 
		return next(new Error('article object not find'));
	var title = req.body.title;
	title = title.replace(/<[^>]+>/g,"","");
	var content = req.body.content;
	// content = content.replace(/</g,"&lt;");
	// content = content.replace(/>/g,"&gt;");
	// content = content.replace(/\n/g,"<br/>");
	// content = content.replace(/\s/g,"&nbsp;");
	var base64Img = req.body.imgPath;
	var imgName =	encrypto(title)+'.png' ;
	base64Img = base64Img.replace(/^data:image\/\w+;base64,/, "");
	var dataBuffer = new Buffer(base64Img, 'base64');
	fs.writeFile(config.BLOGPATH+imgName,dataBuffer, function(err) {
		if(err){
		  res.send(err);
		}else{
		  res.send("保存成功！");
		}
	});
	var articleName = randomName(16)+'.html'
	fs.writeFile(os.homedir()+'/A/'+articleName, content, function(err){
		if (err) {
			console.log(err)
		}
	})
	var data = {
		'type':'article',
		'pass':false,
		'name':title,
		// 'content':content,
		'staticpath':articleName,
		'upUser':req.body.upUser,
		'img':imgName,
		'upTime':new Date().getTime(),
		'tag':req.body.tag,
	}
	req.VandB.insertOne(data, function(){
		res.redirect('/articles/list');
	});
})

router.post('/articleImg', function(req, res, next){
	var form = new multiparty.Form();

	form.parse(req, function(err, fields, files){
		var oldpath = files.articleimg[0].path
		var newPath = os.homedir()+'/VA/'+oldpath.replace(/.*?\//g, '')
		console.log(oldpath)
		console.log(newPath)

		fs.readFile(oldpath, function(err,date){
			fs.writeFile(newPath, date, function(err){
				if (err) {
					console.log(err)
				} else {
					res.writeHead(200, {
						'Content-type':'text/html'
					})
					res.end('/articles/VA/'+oldpath.replace(/.*?\//g, ''))
				}
				fs.unlinkSync(oldpath)
			})
		})
	})
})

router.get('/VA/:name', function(req, res, next){
	console.log(req.params.name)
	fs.readFile(os.homedir()+'/VA/'+req.params.name, function(err, date){
		res.writeHead(200, {
			'Content-type':'image/png'
		})
		res.write(date,'binary')
		res.end()
	})
})

router.post('/imgfile', function(req, res, next){
	try{
		file.newFiles(req,config.BLOGPATH, function(date){
			res.json(date)
		}, function jindu(status){
			req.session.progress = status
		})
	}catch(e){

	}
});

router.get('/imgfile/ajax', function(req, res, next){
	res.json({'progress':req.session.progress})
});


router.get('/list', function(req, res, next){
	if (req.infos!=null && req.infos!='' && req.infos) {
		req.VandB.find({'upUser':""+req.infos._id,'type':"article"}).toArray(function(err, items){
			res.render('list',{'title':'文章','user':req.infos,'articles':items})
		})
	} else {
		res.redirect('/log/login');
	}
});

router.get('/list/:id', function(req, res, next){
	req.VandB.findById(req.params.id, function(err, result) {
		if (err) {
			return next(new Error('article error'));
		}
		fs.readFile(os.homedir()+'/A/'+result.staticpath, function(err, date){
			if (err) {
				console.log(err)
			}
			result.content = date.toString()
			res.json({'article':result})
		})
	})
});

router.delete('/:id', function(req, res, next){
	req.VandB.removeById(req.params.id, function(){
		res.jsonp({status:200})
	})
});

router.get('/read/:id', function(req, res, next){

	new Promise(function(resolve, reject){
		req.VandB.findById(req.params.id, function(err, result) {
			if (err) {
				reject(err);
			}
			console.log(result)
			readA(result.staticpath, function(date){
				if (date == null) {
					console.log(date+'233333')
				} else {
					result.content = date
					resolve(result);
				}
			})
		});
	}).then(function(article){

		req.users.findById(article.upUser,function(err,result) {
			var writer = result;
			fans.existFans(req,writer._id,req.infos._id,function(d) {
			
				if (d.length>0) {

					res.locals.isFans = "true";
				} else {
					res.locals.isFans = "false";
				}

				var keepAT = [];
				keepAT = req.infos.keepAT
				console.log(keepAT);

				res.render('read',{'title':'read '+article.name,
									'user':req.infos, 
									'article':article,
									'writer':writer,
									'tag':artTag[article.tag],});
		
			});
		});

	});

});

router.put('/updata/', function(req, res, next) {
	
	fs.writeFile(os.homedir()+'/A/'+req.body.staticpath, req.body.text, function(err){
		if (err) {
			console.log(err)
		}
		res.status(200).send('ok')
	})
});

router.post('/read/comment/:id', function(req, res, next){
	// console.log(req.body)
	if (req.body.user.userid == null) {
		res.status(400).send('Bad Request');
	} else {
		Comments.insertComments(req, 'article', req.params.id, function(j){
			if (j.status == 200) {
				res.status(200).send(j.data)
			} else {
				res.status(400).send(j.data)
			}
		})
	}
});

router.get('/read/comments/:id', function(req, res, next){
	try{
		Comments.findComments(req, "article", req.params.id, function(j){
			if (j.status == 200) {
				res.json(j.data)
			} else {
				res.status(400).send(j.data)
			}
		})
	}catch(e){
		res.status(404).render('404',{'err':e})
	}
});

router.get('/read/keep/:id', function(req, res, next){
	try{

		if (!req.infos.name) {
			res.status(404).render('404',{'err':'please login'})
		}else{
			keep.insertKeep(req, req.infos.name, 'article', req.params.id, function(d){
				res.send(d)
			})
		}
	}catch(e){
		res.status(404).render('404',{'err':e})
	}
});

router.delete('/read/delkeep/:id',function(req,res,next) {
	keep.removeKeep(req,req.infos.name,
					"article",req.params.id,
					function(d){
						res.send(d);
	});
});

router.post('/read/addfans',function(req,res,next) {

	try{
		if (!req.infos.name) {
			res.status(404).render('404',{'err':'please login'})
		}else{
		fans.insertFans(req,req.body.addfans.name,req.body.addfans.FID,
						function(d){
							res.send(d);
						});
		}
	}catch(e){
		res.status(404).render('404',{'err':e})
	}
});

router.post('/read/refans',function(req,res,next) {

	try{
		if (!req.infos.name) {
			res.status(404).render('404',{'err':'please login'})
		}else{
		fans.removeFans(req,req.body.addfans.name,req.body.addfans.FID,
						function(d){
							res.send(d);
						});
		}
	}catch(e){
		res.status(404).render('404',{'err':e})
	}
});



module.exports = router;